<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="市场名称" prop="marketName">
        <el-input
          v-model="queryParams.marketName"
          placeholder="请输入市场名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="市场类型" prop="marketType">
        <el-select v-model="queryParams.marketType" placeholder="请选择市场类型" clearable size="small" :options="marketTypeOpts">
          <el-option
            v-for="dict in marketTypeOpts"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictLabel"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="省份" prop="province">
        <el-input
          v-model="queryParams.province"
          placeholder="请输入省份"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input
          v-model="queryParams.city"
          placeholder="请输入城市"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区县" prop="area">
        <el-input
          v-model="queryParams.area"
          placeholder="请输入区县"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="街道" prop="street">
        <el-input
          v-model="queryParams.street"
          placeholder="请输入街道"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="招商负责人" prop="investmentManager">
        <el-input
          v-model="queryParams.investmentManager"
          placeholder="请输入招商负责人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in statusOpts"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="预计完成时间" prop="investPlanCompletionTime">
        <!-- <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.investPlanCompletionTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择招商预计完成时间">
        </el-date-picker> -->
        <el-date-picker
          v-model="queryParams.investPlanCompletionTime"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable size="small"
          style="width: 250px"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions">
          </el-date-picker>
      </el-form-item>
      <el-form-item label="启动时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable size="small"
           style="width: 250px"
           value-format="yyyy-MM-dd"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="关闭时间" prop="closingTime">
        <!-- <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.closingTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择关闭时间">
        </el-date-picker> -->
        <el-date-picker
          v-model="queryParams.closingTime"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable size="small"
           style="width: 250px"
           value-format="yyyy-MM-dd"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="完成时间" prop="completionTime">
        <!-- <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.completionTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择完成时间">
        </el-date-picker> -->
        <el-date-picker
          v-model="queryParams.completionTime"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable size="small"
          style="width: 250px"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions">
          </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- v-hasPermi="['xdstore:franchise:add']" -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-add"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['xdstore:franchise:add']"
        >新建</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" border stripe :data="franchiseList" @selection-change="handleSelectionChange" max-height="550px">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="市场名称" align="center" prop="marketName" show-overflow-tooltip  width="180" />
      <el-table-column label="市场类型" align="center" prop="marketType" width="120" />
      <el-table-column label="省份" align="center" prop="province" />
      <el-table-column label="城市" align="center" prop="city" />
      <el-table-column label="区县" align="center" prop="area" />
      <el-table-column label="街道" align="center" prop="street" show-overflow-tooltip  width="180" />
      <el-table-column label="详细地址" align="center" prop="marketAddress" show-overflow-tooltip />
      <el-table-column label="品牌" align="center" prop="brand" width="120" show-overflow-tooltip />
      <el-table-column label="创建人" align="center" prop="custName" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '0'">新建</el-tag>
          <el-tag v-if="scope.row.status === '1'" type="warning">已启动</el-tag>
          <el-tag v-if="scope.row.status === '2'" type="danger">已超期</el-tag>
          <el-tag v-if="scope.row.status === '3'"  type="info">已关闭</el-tag>
          <el-tag v-if="scope.row.status === '4'" type="success">已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="预计完成时间" align="center" prop="investPlanCompletionTime" width="180">
      </el-table-column>
      <el-table-column label="启动时间" align="center" prop="startTime" width="180">
      </el-table-column>
      <el-table-column label="招商负责人" width="120" align="center" prop="investmentManagerName" />
      <el-table-column label="是否超期" align="center" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.overdue" type="danger">已超期</el-tag>
          <el-tag v-else type="success">未超期</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" align="center" prop="storeName" show-overflow-tooltip width="120" />
      <el-table-column label="店铺代码" align="center" prop="storeA8"  width="120" />
      <el-table-column label="完成时间" align="center" prop="completionTime" width="180">
      </el-table-column>=
      <el-table-column label="完成人" align="center" prop="updateByName" />
      <el-table-column label="关闭时间" align="center" prop="closingTime" width="180">
      </el-table-column>
      <el-table-column label="关闭原因" align="center" prop="shutdownReason" show-overflow-tooltip  width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.shutdownReason }}{{ scope.row.otherShutdownReason ? `(${scope.row.otherShutdownReason})` : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关闭人" align="center" prop="closingUserName" />
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['xdstore:franchise:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['xdstore:franchise:delete']"
          >删除</el-button>
        </template>
        <!-- v-hasPermi="['xdstore:franchise:remove']" -->
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改空白网点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="省份" prop="province">
          <el-select v-model="form.province" size="small" @change="selectProvinceFun($event)" placeholder="请选择省份">
              <el-option v-for="dict in provinceOptions" :key="dict.id" :label="dict.regionName" :value="dict.regionName"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select v-model="form.city" size="small" @change="selectCityFun" placeholder="请先选择 省份">
            <el-option v-for="dict in cityOptions" :key="dict.id" :label="dict.regionName" :value="dict.regionName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区县" prop="area">
          <el-select v-model="form.area" size="small" placeholder="请先选择 地市">
            <el-option v-for="dict in districtOptions" :key="dict.id" :label="dict.regionName" :value="dict.regionName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="街道" prop="street">
          <el-input v-model="form.street" placeholder="请输入街道" />
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-select v-model="form.brand" filterable placeholder="请选择品牌">
            <el-option 
              v-for="dict in brandOptions"
              :key="dict.BRAND_CODE"
              :label="dict.BRAND_NAME"
              :value="dict.BRAND_NAME">
            </el-option>
          </el-select>
          <!-- <el-input v-model="form.brand" placeholder="请输入品牌" /> -->
        </el-form-item>
        <el-form-item label="市场类型">
          <el-select v-model="form.marketType" placeholder="请选择市场类型">
            <el-option
              v-for="dict in marketTypeOpts"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictLabel"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市场名称" prop="marketName">
          <el-input v-model="form.marketName" placeholder="请输入市场名称" />
        </el-form-item>
        <el-form-item label="市场详细地址" prop="marketAddress">
          <el-input v-model="form.marketAddress" placeholder="请输入市场详细地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFranchise, getFranchise, delFranchise, addFranchise, updateFranchise, exportFranchise } from "@/api/xdstore/branchInvest";
import requestCrm from '@/utils/requestCrm'
import { listRegionAll } from "@/api/region/region";

const statusOpts = [
  { label: '新建', value: '0' },
  { label: '已启动', value: '1' },
  { label: '已超期', value: '2' },
  { label: '已完成', value: '4' },
  { label: '已关闭', value: '3' },
]
const statusMap = statusOpts.reduce((res, item) => {
  res[item.value] = item.label;
  return res;
}, {});
export default {
  name: "Franchise",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 空白网点表格数据
      franchiseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        isActive: undefined,
        lesseeId: undefined,
        brand: undefined,
        brandCode: undefined,
        province: undefined,
        city: undefined,
        area: undefined,
        street: undefined,
        marketName: undefined,
        marketType: undefined,
        marketAddress: undefined,
        investPlanCompletionTime: undefined,
        startTime: undefined,
        investmentManager: undefined,
        closingTime: undefined,
        shutdownReason: undefined,
        otherShutdownReason: undefined,
        closingUser: undefined,
        completionTime: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      marketTypeOpts: [],
      statusOpts,
      brandOptions: [],
      // 省
      provinceOptions: [],
      // 市
      cityOptions: [],
      // 区
      districtOptions: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("MARTET_TYPE").then(response => {
      this.marketTypeOpts = response.data;
    });
    this.getBrandOptions();
    this.getProvinceOptions();
  },
  filters: {
    statusFilter(val) {
      if (!val) return '无效的状态'
      return statusMap[val] || '未知';
    }
  },
  methods: {
    /** 查询空白网点列表 */
    getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      const rangeDates = [
        {key: 'investPlanCompletionTime', start: 'startInvestPlanDate', end: 'endInvestPlanDate' },
        {key: 'startTime', start: 'startDate', end: 'endDate' },
        {key: 'closingTime', start: 'startClosingDate', end: 'endClosingDate' },
        {key: 'completionTime', start: 'startCompletionDate', end: 'endCompletionDate' },
      ]
      rangeDates.forEach(r => {
        const { key, start, end } = r;
        const dates = params[key];
        if (dates && dates.length > 1) {
          const [startDate, endDate] = dates;
          params[start] = startDate;
          params[end] = endDate;
        }
        params[key] = undefined;
      })
      listFranchise(params).then(response => {
        this.franchiseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    selectProvinceFun(regionName) {
      const that = this;
      that.form.city = '';
      that.form.area = '';
      const r = this.provinceOptions.find(p => p.regionName === regionName);
      that.getCityOptions(r.id);
    },
    selectCityFun(regionName) {
      this.form.area = '';
      const r = this.cityOptions.find(p => p.regionName === regionName);
      this.getDistrictOptions(r.id);
    },
    getProvinceOptions(PID) {
      const that = this;
      listRegionAll({ parentId: '1' }).then(response => {
        that.provinceOptions = response.data || [];
      });
    },
    getCityOptions(PID, city) {
      const that = this;
      listRegionAll({ parentId: PID }).then(response => {
        that.cityOptions = response.data || [];
        if (city) {
          const a = that.cityOptions.find(c => c.regionName === city);
          console.log('city', a)
          if (a) {
            that.getDistrictOptions(a.id);
          }
        }
      });
    },
    getDistrictOptions(CID) {
      const that = this;
      listRegionAll({ parentId: CID }).then(response => {
        that.districtOptions = response.data || [];
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        isActive: undefined,
        lesseeId: undefined,
        brand: undefined,
        brandCode: undefined,
        province: undefined,
        city: undefined,
        area: undefined,
        street: undefined,
        marketName: undefined,
        marketType: undefined,
        marketAddress: undefined,
        investPlanCompletionTime: undefined,
        startTime: undefined,
        investmentManager: undefined,
        closingTime: undefined,
        shutdownReason: undefined,
        otherShutdownReason: undefined,
        closingUser: undefined,
        completionTime: undefined,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    getBrandOptions(){
        requestCrm({
            url:'WxService?method=crmGetBrandAllList',
            method: 'post',
            data: {}
        }).then(res=>{
            this.brandOptions = res.data
        })
      },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加空白网点";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFranchise(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改空白网点";
        const { province, city } = this.form;
        const p = this.provinceOptions.find(p => p.regionName === province);
        if (p) {
          console.log('update', city);
          this.getCityOptions(p.id, city);
        }
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateFranchise(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addFranchise(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除空白网点编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFranchise(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有空白网点数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportFranchise(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>